package com.songcha.sakura.mvvm.sniff

import android.graphics.Bitmap
import android.os.Bundle
import android.view.*
import android.view.inputmethod.EditorInfo
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.just.agentweb.AgentWeb
import com.just.agentweb.WebChromeClient
import com.just.agentweb.WebViewClient
import com.songcha.library_base.base.IOnInputUnFocus
import com.songcha.library_base.mvvm.base.BaseMvvmFragment
import com.songcha.library_base.mvvm.base.BaseRepository
import com.songcha.library_common.helper.SharedPreferenceHelper
import com.songcha.library_common.util.*
import com.songcha.sakura.R
import com.songcha.sakura.ui.adapter.SniffMenuAdapter
import com.songcha.sakura.databinding.FragmentSniffBinding
import com.songcha.sakura.download.DownloadServiceController
import com.songcha.library_common.ui.dialog.CustomDialog
import com.songcha.library_common.ui.dialog.DialogHelper
import com.songcha.library_common.ui.dialog.ListDialog
import com.songcha.library_common.ui.view.BottomNavigationView
import com.songcha.sakura.config.BaseConfig
import com.songcha.sakura.ui.base.BaseComicMvvmFragment
import java.net.URL


class SniffFragment: BaseComicMvvmFragment<SniffViewModel, FragmentSniffBinding>(), TextView.OnEditorActionListener,
    BottomNavigationView.IOnBottomNavigationItemChangeListener,
    IOnInputUnFocus {
    companion object{
        val TAG:String= SniffFragment::class.java.simpleName
    }

    private var mAgentWeb:AgentWeb?=null
    private var mPwMenu:PopupWindow?=null
    private var mHost=""

    override fun getLayoutId(): Int {
        return R.layout.fragment_sniff
    }

    private val mWebViewClient: WebViewClient = object : WebViewClient() {
        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            databinding.rlv.visibility=View.VISIBLE
            viewModel.m3u8List.clear()
        }

        override fun onPageFinished(view: WebView?, url: String?) {
            super.onPageFinished(view, url)
            if(!url.isNullOrBlank()){
                try{
                    mHost=URL(url).host
                }catch (e:Exception){
                    e.printStackTrace()
                }
            }

        }

        override fun shouldInterceptRequest(
            view: WebView?,
            request: WebResourceRequest?
        ): WebResourceResponse? {

            if(request!=null){
                if((request.url.toString().startsWith("http://") || request.url.toString().startsWith("https://")) && request.url.toString().contains(".m3u8")){
                    LogUtil.log("shouldInterceptRequest",request?.url)
                    viewModel.m3u8List.add(request.url.toString())
                }
            }
            return super.shouldInterceptRequest(view, request)
        }

        override fun shouldOverrideUrlLoading(
            view: WebView?,
            request: WebResourceRequest?
        ): Boolean {
            return super.shouldOverrideUrlLoading(view, request)
        }


    }

    private val mWebChromeClient: WebChromeClient = object : WebChromeClient() {
        override fun onProgressChanged(view: WebView?, newProgress: Int) {
            databinding.rlv.setProgress(newProgress)
            if(newProgress==100)
                databinding.rlv.visibility=View.INVISIBLE
        }

    }

    private fun goUrl(){
        val url=databinding.edt.text.toString().trim()
        if(url.isEmpty()){
            ToastUtil.show("url不能为空")
            return
        }
        if(!url.startsWith("http://") && !url.startsWith("https://")){
            ToastUtil.show("无效的url地址")
            return
        }
        SharedPreferenceHelper.setString("sniff","url",url)
        mAgentWeb?.webCreator?.webView?.loadUrl(url)
    }

    private fun clear(){
        databinding.edt.setText("")
    }

    private fun sniff(){
        if(viewModel.m3u8List.size>0){
            val dialog= ListDialog(requireContext(),viewModel.m3u8List)
            dialog.apply {
                setDialogTitle("发现以下m3u8资源")
                setOnListDialogItemClickListener{p->
                    val url=viewModel.m3u8List[p]
                    var title=mHost
                    if(title.isNullOrBlank())
                        title="sniff"
                    var episode=mAgentWeb?.webCreator?.webView?.title

                    val fileName=(System.currentTimeMillis()/1000).toString()+"-"+title+"-"+episode
                    DownloadServiceController.createTask(url,"",fileName)
                    return@setOnListDialogItemClickListener true
                }
            }
            dialog.show()

            /*DialogHelper.showListDialog(requireContext(),"发现以下m3u8资源",viewModel.m3u8List){ p->
                val url=viewModel.m3u8List[p]
                var title=mHost
                if(title.isNullOrBlank())
                    title="sniff"
                var episode=mAgentWeb?.webCreator?.webView?.title

                val fileName=(System.currentTimeMillis()/1000).toString()+"-"+title+"-"+episode
                DownloadServiceController.createTask(url,"",fileName)
                true
            }*/
        }
        else{
            CustomDialog.Companion.Builder(requireContext())
                .setDialogTitle("提示")
                .setDialogMsg("未检测到m3u8资源")
                .create()
                .show()
        }
    }

    private fun download(){
        val url=databinding.edt.text.toString().trim()
        if(url.isEmpty()){
            ToastUtil.show("url不能为空")
            return
        }
        val fileName=(System.currentTimeMillis()/1000).toString()+"-"+"sniff"+"-"+url.substring(url.length-10)
        DownloadServiceController.createTask(url,"",fileName)
    }

    private fun goBack(){
        mAgentWeb?.webCreator?.webView?.goBack()
    }

    private var mOnWebViewTouchListener=object:View.OnTouchListener{
        override fun onTouch(v: View?, event: MotionEvent?): Boolean {
            mPwMenu?.dismiss()
            return false
        }
    }



    override fun initView(savedInstanceState: Bundle?){
        val sniff_url= SharedPreferenceHelper.getString("sniff","url")
        if(sniff_url.isNotEmpty())
            databinding.edt.setText(sniff_url)

        databinding.ivMenu.setOnClickListener {
            if(mPwMenu==null){
                val view=layoutInflater.inflate(R.layout.pop_sniff_menu,null)
                val rcv=view.findViewById<RecyclerView>(R.id.rcv_menu)
                rcv.apply {
                    layoutManager=LinearLayoutManager(requireContext())
                    adapter=SniffMenuAdapter(requireContext(),viewModel.menuList).apply {
                        setOnItemClickListener{a,v,p->
                            when(p){
                                0->{
                                    goBack()
                                }
                                1->{
                                    clear()
                                }
                                2->{
                                    sniff()
                                }
                                3->{
                                    download()
                                }
                            }
                            //mPwMenu?.dismiss()
                        }
                    }
                }

                mPwMenu = PopupWindow(view)
                mPwMenu!!.width=150.dp2px()
                mPwMenu!!.height=200.dp2px()
                mPwMenu!!.animationStyle=(com.songcha.library_common.R.style.dialogTopSlideWindowAnim)
            }

            if(mPwMenu!!.isShowing)
                mPwMenu!!.dismiss()
            else
                mPwMenu!!.showAsDropDown(databinding.ccl,
                    ScreenUtil.getScreenWidth(requireContext())- mPwMenu!!.width,5.dp2px())
        }


        mAgentWeb=AgentWeb.with(this)
            .setAgentWebParent(databinding.llAwv, LinearLayout.LayoutParams(-1, -1))
            .closeIndicator()
            .setWebChromeClient(mWebChromeClient)
            .setWebViewClient(mWebViewClient)
            .createAgentWeb()
            .ready()
            .go("https://www.baidu.com")

        mAgentWeb!!.webCreator?.webView?.setOnTouchListener(mOnWebViewTouchListener)

        /*if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            mAgentWeb!!.webCreator?.webView?.setOnScrollChangeListener(@RequiresApi(Build.VERSION_CODES.M)
            object :View.OnScrollChangeListener{
                override fun onScrollChange(
                    v: View?,
                    scrollX: Int,
                    scrollY: Int,
                    oldScrollX: Int,
                    oldScrollY: Int
                ) {

                }

            })
        }*/

        databinding.edt.setOnEditorActionListener(this)

    }

    override fun onResume() {
        super.onResume()

    }


    override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
        if(actionId==EditorInfo.IME_ACTION_SEARCH){
            mPwMenu?.dismiss()
            goUrl()
            v.let {
                KeyBoardUtil.closeKeyboard(v!!)
            }
            return true
        }
        return false
    }

    override fun onBottomNavigationItemChange(position: Int,tag:String) {
        mPwMenu?.dismiss()
    }

    override fun onInputUnFocus() {
        mPwMenu?.dismiss()
    }



}